package com.xiaol.springbootredis.security.jjwt;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.servlet.ServletException;
import java.util.Date;

/**
 * token check
 */
public class JwtUtil {
    final static String base64EncodedSecretKey = "hooray";//私钥
    final static long TOKEN_EXP = 1000 * 60;//过期时间,测试使用60秒

    public static String getToken(String userName) {
        long nowMillis = System.currentTimeMillis();//生成JWT的时间
        Date now = new Date(nowMillis);
        Date expired = new Date(nowMillis + TOKEN_EXP);

        return Jwts.builder()
                .setSubject(userName)
                .claim("roles", "user")
                .setIssuedAt(now)
                .setExpiration(expired) /*过期时间*/
                .signWith(SignatureAlgorithm.HS256, base64EncodedSecretKey)
                .compact();
    }

    /**
     * @Desc:检查token,只要不正确就会抛出异常
     **/
    public static String checkToken(String token) throws ServletException {
        try {
            final Claims claims = Jwts.parser().setSigningKey(base64EncodedSecretKey).parseClaimsJws(token).getBody();
            return claims.getSubject();
        } catch (ExpiredJwtException e1) {
            throw new ServletException("token expired");
        } catch (Exception e) {
            throw new ServletException("other token exception");
        }
    }
}